package com.clgc.eduservice.controller;


import com.alibaba.excel.EasyExcel;
import com.clgc.baseservice.exception.MyException;
import com.clgc.eduservice.entity.EduStudent;
import com.clgc.eduservice.entity.StudentLoginEntity;
import com.clgc.eduservice.entity.excel.StudentExcel;
import com.clgc.eduservice.listener.StudentListener;
import com.clgc.eduservice.service.EduStudentService;
import com.clgc.utils.MD5Utils;
import com.clgc.utils.R;
import com.clgc.utils.ResultCode;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 学生表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-04-27
 */
@RestController
@RequestMapping("/eduservice/edu-student")
@CrossOrigin
public class EduStudentController {
    @Autowired
    private EduStudentService eduStudentService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private StudentListener studentListener;

    @ApiOperation("学生注册批量入库（通过手动输入）")
    @PostMapping("/studentRegisterByList")
    public R studentRegisterByList(@RequestBody List<EduStudent> studentList) {
        for (EduStudent student : studentList) {
            String pwd = student.getPwd();
            String md5Encode = MD5Utils.MD5Encode(pwd);
            student.setPwd(md5Encode);
        }
        boolean flag = eduStudentService.saveBatch(studentList);
        return flag ? R.ok().message("导入成功") : R.error().message("导入失败");
    }

    @ApiOperation("学生注册批量入库（excel）")
    @PostMapping("/studentRegisterByExcel")
    public R studentRegisterByExcel(MultipartFile multipartFile) {
        try {
            EasyExcel.read(multipartFile.getInputStream(), StudentExcel.class, studentListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException("导入学生表失败", ResultCode.ERROR);
        }
        return R.ok().message("学生表导入成功");
    }

    @ApiOperation(value = "学生登录")
    @PostMapping("/login")
    public R studentLogin(@RequestBody StudentLoginEntity studentLoginEntity, HttpServletRequest request) {
        return eduStudentService.login(studentLoginEntity.getUsername(),studentLoginEntity.getPwd(),request);
    }

    @ApiOperation(value = "获取学生当前账户信息")
    @GetMapping("/student/info")
    public EduStudent getTeacherInfo(Principal principal) {
        if (principal == null) {
            return null;
        }
        String username = principal.getName();
        EduStudent student = eduStudentService.getStudentByUsername(username);
        //密码不可见
        if (null == student) {
            return null;
        }
        student.setPwd(null);
        return student;
    }

    @ApiOperation(value = "注销")
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        String authHeader = request.getHeader(tokenHeader);
        HashMap<String, Object> tokenMap = new HashMap<>();
        if (null != tokenHeader) {
            String token = authHeader.substring(tokenHead.length()) + 1;
            tokenMap.put("token", token);
            tokenMap.put("tokenHead", tokenHead);
        }
        return R.ok().message("注销成功").data(tokenMap);
    }

    @ApiOperation(value = "更新当前用户信息")
    @PostMapping("/updateInfo")
    public R updateStudentInfo(@RequestBody EduStudent eduStudent,HttpServletRequest request) {
        String pwd = eduStudent.getPwd();
        HashMap<String, Object> tokenMap = new HashMap<>();
        if (null != pwd) {
            String md5Pwd = MD5Utils.MD5Encode(pwd);
            eduStudent.setPwd(md5Pwd);
            //如果密码被修改，强制退出登录
            String tokenHeader = request.getHeader(this.tokenHeader);
            String token = tokenHeader.substring(tokenHead.length()) + 1;
            tokenMap.put("token", token);
            tokenMap.put("tokenHead", tokenHead);
        }
        boolean flag = eduStudentService.updateById(eduStudent);
        return flag ? R.ok().message("修改成功").data(tokenMap) : R.error().message("修改失败");
    }
}

